// popup.js
(function() {
  const button = document.getElementById('toggle');
  const status = document.getElementById('status');
  
  // 状态管理
  async function updateUI() {
    try {
      const { enabled } = await chrome.storage.local.get('enabled');
      button.textContent = enabled ? 'ON' : 'OFF';
      button.className = enabled ? 'on' : 'off';
      status.textContent = `状态: ${enabled ? '运行中' : '已关闭'}`;
    } catch (error) {
      console.error('状态更新失败:', error);
      button.textContent = '错误';
      status.textContent = '无法读取存储';
    }
  }

  // 切换操作
  button.addEventListener('click', async () => {
    try {
      const { enabled: currentState } = await chrome.storage.local.get('enabled');
      const newState = !currentState;
      
      await chrome.storage.local.set({ enabled: newState });
      
      const [tab] = await chrome.tabs.query({ 
        active: true, 
        currentWindow: true,
        status: 'complete'
      });
      
      if (tab?.id) {
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          files: ['content.js']
        });
        chrome.tabs.sendMessage(tab.id, { enabled: newState });
      }
      
      await updateUI();
    } catch (error) {
      console.error('切换操作失败:', error);
      status.textContent = '通信失败，请刷新页面';
    }
  });

  // 初始化
  (async function init() {
    button.textContent = '加载中...';
    await new Promise(resolve => setTimeout(resolve, 500)); // 等待存储初始化
    chrome.storage.local.get('enabled', () => {
      updateUI();
      chrome.tabs.query({ active: true, currentWindow: true }, updateUI);
    });
  })();
})();